package com.dengke.hellospringmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LogInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		long startTime=System.currentTimeMillis();
		System.out.println("\n---------LogInterceptor.perHandler--------");
		System.out.println("Requset URL:"+request.getRequestURL());
		System.out.println("Start Time:"+System.currentTimeMillis());
		request.setAttribute("startTime", startTime);
		//if it return true ,it means request will continue to come to its destination
		return true;
	}

	//controller send viewandmodel to view,so you can  add attributes in the modelandview 
	//and can use that in the view page
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("\n--------LoginInterceptor.postHandle--------");
		System.out.println("Request URL:"+request.getRequestURL());
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("\n-------- LogInterception.afterCompletion --- ");
		 
        long startTime = (Long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        System.out.println("Request URL: " + request.getRequestURL());
        System.out.println("End Time: " + endTime);
 
        System.out.println("Time Taken: " + (endTime - startTime));
	}

	//并发处理
	@Override
	public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterConcurrentHandlingStarted(request, response, handler);
	}

}
